<?php

namespace app\controller;


use app\BaseController;
use app\common\TencentIm;
use app\model\Sms;
use app\model\Users;
use app\Request;
use app\tool\Http;
use think\db\exception\DbException;
use think\Exception;
use think\facade\Db;
use think\facade\Log;
use think\response\Json;

class PageController extends BaseController
{
	
	protected array $middleware = ['Login' => [
		'except' => ['build_users', 'login', 'sendSms'],
	]];
	protected $head_image = '/uploads/20231115/f57ebce8a72b823912904fe76eda0909.png';
	
	
	/**
	 * 批量生成用户
	 * @return void
	 */
	function build_users()
	{
		$TencentIm = TencentIm::getInstance();
		
		for ($i = 1; $i <= 50; $i++) {
			$rand = mt_rand(10000000, 99999999);
			do {
				$rand++;
			} while (Users::where(['invite_code' => $rand])->find());
			// 启动事务
			Db::startTrans();
			try {
				$ret = Users::create([
					'nickname' => '用户' . $rand,
					'mobile' => $rand,
					'head_image' => $this->head_image,
					'invite_code' => $rand,
					'logintime' => time()
				]);
				$ret = json_decode($TencentIm->account_import((string)$ret->id, $ret->nickname, config('app.static_host') . $ret->head_image));
				if ($ret->ErrorCode != 0) {
					throw new Exception($ret->ErrorInfo);
				}
				// 提交事务
				Db::commit();
			} catch (Exception $e) {
				// 回滚事务
				Db::rollback();
				writeJson(0, $e->getMessage());
			}
		}
		writeJson();
	}
	
	/**
	 * 登录
	 */
	function login(Request $request)
	{
		$mobile = $request->post('mobile');
		$captcha = $request->post('captcha');
		$wx_code = $request->post('wx_code','');
		Log::record('登录');
		Log::record($wx_code);
		$qq_code = $qq_openid = $request->post('qq_code','');
		$code = $request->post('code/d',0);
		$wechat_openid = '';
		$users = '';
		if (empty($wx_code)&&empty($code)&&empty($qq_code)){
			writeJson(0,'参数错误');
		}
		if (!empty($captcha) && !empty($mobile)) {
			try {
				validate(\app\validate\Sms::class)->check(['mobile' => $mobile, 'event' => 'mobilelogin','code'=>$code]);
			} catch (\Exception $e) {
				writeJson(0, $e->getMessage());
			}
			//todo 更换验证码
			$ret = \app\common\Sms::check($mobile, $captcha, 'mobilelogin');
			if (!$ret && $captcha != '8520') {
				writeJson(0, '验证码不正确');
			}
			
			//  存储登录态
			$users = Users::where(['mobile' => $mobile,'code'=>$code])->find();
		} elseif (!empty($wx_code)) {
			$res = Http::get('https://api.weixin.qq.com/sns/oauth2/access_token', [
				'appid' => 'wxcb3a0e9976ee4226',
				'secret' => 'feb8290893b72da6f005f50d7f9c6f3e',
				'code' => $wx_code,
				'grant_type' => 'authorization_code'
			]);
			$json_obj = json_decode($res);
			
			if (empty($json_obj->openid)) {
				writeJson(0, $json_obj->errmsg);
			}
			$users = Users::where('wechat_openid', $json_obj->openid)->find();
			$wechat_openid = $json_obj->openid;
		} elseif(!empty($qq_code)) {
			$users = Users::where('qq_openid', $qq_code)->find();
		}else{
			writeJson(0, '参数错误');
		}
		
		
		if ($users) {
			$users->login_time = time();
			$users->save();
			
		} else {
			$rand = rand(1000000, 9999999);
			do {
				$rand++;
			} while (Users::where(['invite_code' => $rand])->find());
			//注册
			$users = Users::create([
				'nickname' => "用户$rand",
				'mobile' => $mobile,
				'head_image' => $this->head_image,
				'invite_code' => $rand,
				'logintime' => time(),
				'wechat_openid' => $wechat_openid,
				'qq_openid' => $qq_openid,
				'code'=>$code
			]);
			$users->tim_id = 'hk_'.$users->id;
			$users->save();
			$TencentIm = TencentIm::getInstance();
			$ret = json_decode($TencentIm->account_import($users->id, "用户$rand", config('app.static_host') . $this->head_image));
			if ($ret->ErrorCode != 0) {
				writeJson(0, $ret->ErrorInfo);
			}
		}
		$token = ['users_id' => $users->id];
		writeJson(['token' => sign_token($token)]);
	}
	
	/**
	 * 发送验证码
	 * event 验证码类型:登录=mobilelogin,注册=register,换绑手机号=changemobile,更改密码=changepwd,重置密码=resetpwd
	 * @param Request $request
	 * @return Json
	 * @throws DbException
	 */
	function sendSms(Request $request)
	{
		$params = $request->param();
		$event = $params['event'] ?? 'register';
		
		try {
			validate(\app\validate\Sms::class)->check($params);
		} catch (\Exception $e) {
			writeJson(0, $e->getMessage());
		}
		$ipSendTotal = Sms::where(['ip' => $request->ip()])->whereTime('createtime', '-1 hours')->count();
		$last = Sms::where(['mobile' => $params['mobile'], 'event' => $event])->order('id', 'DESC')->find();
		if (($last && time() - $last->getData('createtime') < 60) || $ipSendTotal >= 10) {
			writeJson(0, '发送频繁');
		}
		if ($event) {
			$userinfo = Users::getByMobile($params['mobile']);
			if ($event == 'register' && $userinfo) {
				//已被注册
				writeJson(0, '已被注册');
			} elseif ($event == 'changemobile' && $userinfo) {
				//被占用
				writeJson(0, '已被占用');
			} elseif (in_array($event, ['changepwd', 'resetpwd']) && !$userinfo) {
				//未注册
				writeJson(0, '未注册');
				
			}
		}
	
		$ret = \app\common\Sms::send($params['code'],$params['mobile'], null, $event);
		if ($ret) {
			writeJson();
		} else {
			writeJson(0, '发送失败');
		}
	}
	
	
}